const { getToken } = require("../common/getToken/index.js");
const { getNewTicket } = require("./getNewTicket.js");
const { util, BaseErr } = require("utils");
const { updateTokenInfo } = require("../../db/index.js");
const { Type_Wx_Web_Ticket, GetTokenType, TokenStatus } = require("../../constEnum.js");

// 处理新token
async function requestNewTicket(appId, appSecret, cache, provider) {
    let docId = cache._id;
    // 没有缓存,  要请求
    let [new_err, new_token] = await getNewTicket(appId, appSecret, provider);
    if (!util.nilValue(new_err)) {
        if (cache.tokenStatus !== TokenStatus.invalid) {
            // 写入数据库,  状态是 无效
            await updateTokenInfo(docId, {
                tokenStatus: TokenStatus.invalid,
            });
        }
        return [new_err, null];
    }
    // 写入数据库
    // 提前15分钟过期
    let expireIn = Math.max((new_token.expires_in - 15 * 60) * 1000, 0);
    let updateDate = new Date().getTime();
    let updateDateDes = util.baseDateDes(updateDate);
    let outDate = updateDate + expireIn;
    let outDateDes = util.baseDateDes(outDate);
    let saveTokenObj = {
        token: new_token.ticket,
        tokenStatus: TokenStatus.valid,
        requestCount: 0,
        updateDate,
        updateDateDes,
        outDate,
        outDateDes,
    };
    let [save_err, _] = await updateTokenInfo(docId, saveTokenObj);
    if (!util.nilValue(save_err)) {
        console.log("保存  到表 失败 ", save_err);
    }
    return [null, new_token.ticket];
}
// 获取 ticket
async function getWxWebTicket(appId, appSecret, provider) {
    let [err, res] = await getToken(Type_Wx_Web_Ticket, appId);
    if (!util.nilValue(err)) {
        return [err, null];
    }
    // [null, { flag: false, message: "要请求新的哦", type: GetTokenType.getNew }];
    let { flag, type, doc } = res || {};
    if (flag === true) {
        return [null, doc.token];
    }
    if (type === GetTokenType.getNew) {
        // 要请求 新的token
        return await requestNewTicket(appId, appSecret, doc, provider);
    }
    return [new BaseErr(-5003, "获取ticket失败"), null];
}

module.exports = {
    getWxWebTicket,
};
